using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using MyUnityLib.ClassExtension;
using MyUnityLib.Tool;
using MyUnityLib.UI;

namespace ProductExpirationAssistant
{
    public class OffShelfProductionDateItemUI : TableViewCell
    {
        /// <summary>保质期</summary>
        private InputField m_QualityGuaranteePeriod;
        /// <summary>保质期单位</summary>
        private Dropdown m_QualityGuaranteePeriodUnit;

        /// <summary>提前下架天数</summary>
        private InputField m_DaysInAdvance;

        /// <summary>下架生产日期</summary>
        private Text m_OffShelfProductionDate;
        /// <summary>过期生产日期</summary>
        private Text m_ExpiredProductionDate;

        private OffShelfProductionDateQuery m_Data = null;

        private void Awake()
        {
            m_QualityGuaranteePeriod = transform.FindComponentByPath<InputField>("QualityGuaranteePeriod/QualityGuaranteePeriodDate");
            m_QualityGuaranteePeriodUnit = transform.FindComponentByPath<Dropdown>("QualityGuaranteePeriod/Unit");
            m_DaysInAdvance = transform.FindComponentByPath<InputField>("DaysInAdvance/DaysInAdvanceDate");
            m_OffShelfProductionDate = transform.FindComponentByPath<Text>("OffShelfProductionDate/Text");
            m_ExpiredProductionDate = transform.FindComponentByPath<Text>("ExpiredProductionDate/Text");

            UITool.BindInputFieldEndEdit(transform, OnInputFieldEndEdit, true);
            UITool.BindButtonEvent(transform, "DeleteBtn", DeleteBtn);
        }
        private void OnEnable()
        {
            m_QualityGuaranteePeriodUnit.onValueChanged.AddListener(OnQGPUnitChanged);
            Messenger.AddListener<bool>(EventName.LockOffShelfProductionDateItem, OnLockUIRespondChanged);
        }
        private void OnDisable()
        {
            m_QualityGuaranteePeriodUnit.onValueChanged.RemoveListener(OnQGPUnitChanged);
            try
            {
                Messenger.RemoveListener<TipPopupPanel.ReplyKind>(EventName.CloseTipPopup, OnCloseTipPopup);
                Messenger.RemoveListener<bool>(EventName.LockOffShelfProductionDateItem, OnLockUIRespondChanged);
            }
            catch (System.Exception) { }
        }

        public void Refresh(OffShelfProductionDateQuery data = null)
        {
            if (data != null) m_Data = data;
            if (m_Data == null) return;

            m_QualityGuaranteePeriod.text = m_Data.qualityGuaranteePeriod.num.ToString();

            // Refresh()修改m_QualityGuaranteePeriodUnit.value可能会触发OnQGPUnitChanged()导致重新加载列表，重新加载列表又会调用Refresh()。这会导致一定次数的循环甚至是死循环
            // 解决方法：在Refresh()中修改m_QualityGuaranteePeriodUnit.value，不对onValueChanged进行监听。
            m_QualityGuaranteePeriodUnit.onValueChanged.RemoveListener(OnQGPUnitChanged);
            m_QualityGuaranteePeriodUnit.value = (int)m_Data.qualityGuaranteePeriod.unit;
            m_QualityGuaranteePeriodUnit.onValueChanged.AddListener(OnQGPUnitChanged);

            m_DaysInAdvance.text = m_Data.daysInAdvance.ToString();
            RefreshOffShelfProductionDate();
        }

        private void OnInputFieldEndEdit(InputField inputField)
        {
            inputField.text = inputField.text.RemoveSpace();
            string errorTip = string.Empty;

            switch (inputField.name)
            {
                case "QualityGuaranteePeriodDate":
                    {
                        if (int.TryParse(inputField.text, out int ret))
                        {
                            if (ret != m_Data.qualityGuaranteePeriod.num)
                            {
                                m_Data.qualityGuaranteePeriod.num = ret;
                                OnChangeQueryData();
                                RefreshOffShelfProductionDate();
                            }
                        }
                        else
                        {
                            // 解析失败，格式不正确。还原显示
                            errorTip = $"[{inputField.text}] 格式错误";
                            inputField.text = m_Data.qualityGuaranteePeriod.num.ToString();
                        }
                        break;
                    }
                case "DaysInAdvanceDate":
                    {
                        if (int.TryParse(inputField.text, out int ret))
                        {
                            if (ret != m_Data.daysInAdvance)
                            {
                                m_Data.daysInAdvance = ret;
                                OnChangeQueryData();
                                RefreshOffShelfProductionDate();
                            }
                        }
                        else
                        {
                            // 解析失败，格式不正确。还原显示
                            errorTip = $"[{inputField.text}] 格式错误";
                            inputField.text = m_Data.daysInAdvance.ToString();
                        }
                        break;
                    }
                default:
                    {
                        Debug.LogError($"未知[{inputField.name}]");
                        break;
                    }
            }

            if (errorTip.IsNotEmpty())
            {
                Messenger.Broadcast<TipPopupPanel.Kind, string>(EventName.ShowTipPopup, TipPopupPanel.Kind.Yes, errorTip);
            }
        }

        /// <summary>保质期单位改变</summary>
        private void OnQGPUnitChanged(int no)
        {
            m_Data.qualityGuaranteePeriod.unit = (DateUnit)no;
            OnChangeQueryData();
            RefreshOffShelfProductionDate();
        }

        /// <summary>刷新下架生产日期的显示</summary>
        private void RefreshOffShelfProductionDate()
        {
            m_OffShelfProductionDate.text = m_Data.CalOffShelfProductionDate().ToString("yyyy.MM.dd");
            m_ExpiredProductionDate.text = m_Data.CalExpiredProductionDate().ToString("yyyy.MM.dd");
        }

        private void DeleteBtn(Button button)
        {
            Messenger.AddListener<TipPopupPanel.ReplyKind>(EventName.CloseTipPopup, OnCloseTipPopup);
            Messenger.Broadcast<TipPopupPanel.Kind, string>(EventName.ShowTipPopup, TipPopupPanel.Kind.Yes_No, "确认删除该记录");
        }

        private void OnCloseTipPopup(TipPopupPanel.ReplyKind kind)
        {
            if (kind == TipPopupPanel.ReplyKind.Yes)
            {
                OffShelfProductionDateQueryDatabase.ins.Remove(m_Data);
                m_Data = null;
                Messenger.Broadcast(EventName.ReloadOffShelfProductionDatePanel);
            }

            Messenger.RemoveListener<TipPopupPanel.ReplyKind>(EventName.CloseTipPopup, OnCloseTipPopup);
        }

        private void OnChangeQueryData()
        {
            OffShelfProductionDateQueryDatabase.ins.Sort();
            Messenger.Broadcast(EventName.ReloadOffShelfProductionDatePanel);
            OffShelfProductionDateQueryDatabase.ins.Save();
        }

        private void OnLockUIRespondChanged(bool l) { SetLockUIRespond(l); }

        public void SetLockUIRespond(bool l)
        {
            foreach (var selection in transform.FindComponentsInChildren<Selectable>(true))
            {
                selection.interactable = !l;
            }
        }
    }
}